
const JWT = require('jsonwebtoken')

const { empError } = require('../constant/error.type')
const { JWT_SECRET } = require('../config/config.default')
const { findEmpByPhoneAndPwd, updateById, createEmp, queryAll } = require('../service/employee.service')

class EmployeeController {

    async login(ctx, next) {
        //拿到数据调用service中的方法处理
        const { phone, password } = ctx.request.body
        const res = await findEmpByPhoneAndPwd(phone, password)
        ctx.status = 200
        if (res) {
            ctx.body = {
                code: '200',
                message: "登录成功",
                data: {
                    user: res,
                    token: JWT.sign(res, JWT_SECRET, { expiresIn: '1d' })
                }
            }
            return
        }
        ctx.app.emit('error', empError, ctx)
    }

    async updatePwd(ctx) {
        const { password } = ctx.request.body
        const emp = ctx.state.emp
        emp.password = password
        await updateById(emp)
        ctx.body = {
            code: '200',
            message: '修改成功'
        }
    }

    async create(ctx) {
        const res = await createEmp(ctx.request.body)
        console.log(res);

        ctx.body = {
            code: '200',
            message: '添加成功'
        }
    }

    async update(ctx) {
        const emp = ctx.request.body
        emp.id = ctx.state.emp.id
        await updateById(emp)
        ctx.body = {
            code: '200',
            message: '修改成功'
        }
    }

    async query(ctx) {
        const { pageNum = 1, pageSize = 10, ...whereOpt } = ctx.request.query
        // const {onDuty,empName} = ctx.request.query
        // console.log(onDuty);
        // console.log(empName);
        // const whereOpt = {  }
        // onDuty && Object.assign(whereOpt,{onDuty})
        // empName && Object.assign(whereOpt,{empName})

        const res = await queryAll(pageNum, pageSize, whereOpt)

        ctx.body = {
            code: '200',
            message: '查询成功',
            data: res
        }
    }

    async updateOnDuty(ctx) {
        const emp = {
            id: ctx.request.params.id,
            onDuty: 0
        }
        const res = await updateById(emp)
        if (res) {
            ctx.body = {
                code: '200',
                message: '离职成功'
            }
        } else {
            ctx.body = {
                code: '200',
                message: '员工已离职'
            }
        }
    }

    async resetPwd(ctx) {
        const emp = {}
        emp.id = ctx.request.body.id
        emp.password = '123456'
        // console.log(emp);
        updateById(emp)
        ctx.body = {
            code: '200',
            message: '密码重置成功'
        }
    }
}

module.exports = new EmployeeController()